package livesun.justiceeternal.db.love;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;
import livesun.justiceeternal.db.LoveBeanDao;
import livesun.justiceeternal.db.task.AbsTemplateDbTask;
import livesun.justiceeternal.utils.HandlerFactory;

public class LoveQueryTask <T>  extends AbsTemplateDbTask<T> {
    public LoveQueryTask(Class<? extends T> t) {
        super(t);
    }

    @Override
    public final void onTaskExecute(AbstractDao<T, ?> dao) {
        if (dao == null) {
            notifyFinished(new ArrayList<T>());
            return;
        }
        try {
            QueryBuilder<T> builder = dao.queryBuilder();
            onPrepareBuilder(builder);
            final List<T> list = builder.list();
            onQueryPreHandle(list);
            notifyFinished(list);
        } catch (Throwable e) {
            e.printStackTrace();
            notifyFinished(new ArrayList<T>());
        }
    }
    private void notifyFinished(final List<T> list) {
        HandlerFactory.main().post(new Runnable() {
            @Override
            public void run() {
                onQueryFinished(list);
            }
        });
    }

    public void onPrepareBuilder(QueryBuilder<T> builder) {
        builder.orderDesc(LoveBeanDao.Properties.SaveTime);
    }

    public void onQueryPreHandle(List<T> notes) {
    }

    public void onQueryFinished(List<T> notes) {
    }
}
